package com.menghao.sso.server.model.ticket;

import com.menghao.sso.server.registry.ExpirationPolicy;
import lombok.Data;

@Data
public abstract class AbstractTicket implements Ticket {

    /**
     * 过期策略
     */
    private final ExpirationPolicy expirationPolicy;

    /**
     * Ticket唯一ID
     */
    private final String id;

    /**
     * 相关联的TicketGrantingTicket.
     */
    private final TicketGrantingTicket ticketGrantingTicket;

    /**
     * 最近一次被使用的时间.
     */
    private long lastTimeUsed;

    /**
     * Ticket被使用的次数
     */
    private int countOfUses;

    public AbstractTicket(final String id, final TicketGrantingTicket ticket, final ExpirationPolicy expirationPolicy) {
        if (expirationPolicy == null || id == null) {
            throw new IllegalArgumentException(
                    "id and expirationPolicy are required parameters.");
        }
        this.id = id;
        this.lastTimeUsed = System.currentTimeMillis();
        this.expirationPolicy = expirationPolicy;
        this.ticketGrantingTicket = ticket;
    }

    public final void incrementCountOfUses() {
        this.countOfUses++;
    }

    public final void updateLastTimeUsed() {
        this.lastTimeUsed = System.currentTimeMillis();
    }

    public final TicketGrantingTicket getGrantingTicket() {
        return this.ticketGrantingTicket;
    }

    public final boolean isExpired() {
        return this.expirationPolicy.isExpired(this) || isExpiredInternal();
    }

    protected abstract boolean isExpiredInternal();
}
